package com.tan.lbs.servlet;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.swing.ImageIcon;

import com.jspsmart.upload.*;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.*;
import com.sun.image.codec.jpeg.*;
import com.tan.lbs.dao.DialogNodeDAO;
import com.tan.lbs.dao.GameDAO;
import com.tan.lbs.dao.ItemDAO;
import com.tan.lbs.dao.MediaDAO;
import com.tan.lbs.dao.NPCDAO;
import com.tan.lbs.dao.QuestDAO;
import com.tan.lbs.dao.impl.DialogNodeDAOImpl;
import com.tan.lbs.dao.impl.GameDAOImpl;
import com.tan.lbs.dao.impl.ItemDAOImpl;
import com.tan.lbs.dao.impl.MediaDAOImpl;
import com.tan.lbs.dao.impl.NPCDAOImpl;
import com.tan.lbs.dao.impl.QuestDAOImpl;
import com.tan.lbs.entity.DialogNode;
import com.tan.lbs.entity.Game;
import com.tan.lbs.entity.Item;
import com.tan.lbs.entity.Media;
import com.tan.lbs.entity.NPC;
import com.tan.lbs.entity.Quest;

@WebServlet("/upload")
public class UploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private final static long FILE_MAX_SIZE = 5000000;
	private final static String FILE_EXTEND_NAME = "jpg,JPG,gif,GIF,png,PNG";
	private final static String UPLOAD_DIRECTORY = "/uploadFiles/";
	private ServletConfig config;
	private MediaDAO mediaDAO;
	private GameDAO gameDAO;
	private ItemDAO itemDAO;
	private NPCDAO npcDAO;
	private QuestDAO questDAO;
	private DialogNodeDAO dialogNodeDAO;

	final public void init(ServletConfig config) throws ServletException {
		this.config = config;
		mediaDAO = new MediaDAOImpl();
		gameDAO = new GameDAOImpl();
		itemDAO = new ItemDAOImpl();
		npcDAO = new NPCDAOImpl();
		questDAO = new QuestDAOImpl();
		dialogNodeDAO = new DialogNodeDAOImpl();
	}

	final public ServletConfig getServletConfig() {
		return config;
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		SmartUpload mySmartUpload = new SmartUpload();

		mySmartUpload.initialize(config, request, response);
		mySmartUpload.setAllowedFilesList(FILE_EXTEND_NAME);
		mySmartUpload.setMaxFileSize(FILE_MAX_SIZE);
		
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+
				request.getContextPath()+"/" + UPLOAD_DIRECTORY;  
	
		
		String mediaID = "";
		String fileName = "";
		boolean isUploaded = false;
		try {
			mySmartUpload.upload();
			
			
			String requestUpload = mySmartUpload.getRequest().getParameter("requestUpload");
			String gameObjID = mySmartUpload.getRequest().getParameter("gameObjID");
			String gameID = mySmartUpload.getRequest().getParameter("gameID");
			
			com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(
					0);

			Media m = new Media();
			m.setGameID(gameID);
			m.setPath(basePath);
			m.setType(myFile.getFileExt());
			mediaID = mediaDAO.create(m);

			fileName = mediaID + "." + myFile.getFileExt();
			myFile.saveAs(UPLOAD_DIRECTORY + fileName, SmartUpload.SAVE_VIRTUAL);
			uploadUpdate(requestUpload,mediaID,gameObjID);
			isUploaded = true;
		} catch (Exception e) {
			e.printStackTrace();
			response.getWriter().write("<div id='uploadError'><b>Upload Error.</b></div>");
		}
		
		String wholePath = basePath + fileName;
		String backMessage = "<table><tr align='center'><td align='center'><img id='pic' src='"+wholePath+"'/></td></tr></table><div id='returnMediaID' style='display:none'>" + mediaID + "</div>" + 
				"<div id='returnMediaPath' style='display:none'>" + wholePath + "</div>";
		if(!isUploaded) {
			backMessage += "<div id='uploadError'><b>Cannot upload because: It is not png, jpg or gif format. Or It is too big.</b></div>";
		}
		response.getWriter().write(backMessage);
	}

	private void uploadUpdate(String requestUpload, String mediaID,String gameObjID) {
		if(requestUpload.equalsIgnoreCase("gameicon")) {
			Game game = gameDAO.readByID(gameObjID);
			if(game.getIconID()!=null) {
				game.setIconID(null);
				mediaDAO.delete(game.getIconID());
			}
			game.setIconID(mediaID);
			gameDAO.update(game);
		} else if(requestUpload.equalsIgnoreCase("gamecover")) {
			Game game = gameDAO.readByID(gameObjID);
			if(game.getGameCoverID()!=null) {
				game.setGameCoverID(null);
				mediaDAO.delete(game.getGameCoverID());
			}
			game.setGameCoverID(mediaID);
			gameDAO.update(game);
		} else if(requestUpload.equalsIgnoreCase("itemicon")) {
			Item item = itemDAO.readByID(gameObjID);
			if(item.getIconID()!=null) {
				item.setIconID(null);
				mediaDAO.delete(item.getIconID());
			}
			item.setIconID(mediaID);
			itemDAO.update(item);
		} else if(requestUpload.equalsIgnoreCase("itemcontainedmedia")) {
			Item item = itemDAO.readByID(gameObjID);
			if(item.getContainedMediaID()!=null) {
				item.setContainedMediaID(null);
				mediaDAO.delete(item.getContainedMediaID());
			}
			item.setContainedMediaID(mediaID);
			itemDAO.update(item);
		} else if(requestUpload.equalsIgnoreCase("npcIcon")) {
			NPC npc = npcDAO.readByID(gameObjID);
			if(npc.getIconID()!=null) {
				npc.setIconID(null);
				mediaDAO.delete(npc.getIconID());
			}
			npc.setIconID(mediaID);
			npcDAO.update(npc);
		} else if(requestUpload.equalsIgnoreCase("npcFigure")) {
			NPC npc = npcDAO.readByID(gameObjID);
			if(npc.getFigureID()!=null) {
				npc.setFigureID(null);
				mediaDAO.delete(npc.getFigureID());
			}
			npc.setFigureID(mediaID);
			npcDAO.update(npc);
		} else if(requestUpload.equalsIgnoreCase("dNodeContainedMedia")) {
			DialogNode dialogNode = dialogNodeDAO.readByID(gameObjID);
			if(dialogNode.getContainedMediaID()!=null) {
				dialogNode.setContainedMediaID(null);
				mediaDAO.delete(dialogNode.getContainedMediaID());
			}
			dialogNode.setContainedMediaID(mediaID);
			dialogNodeDAO.update(dialogNode);
		} else if(requestUpload.equalsIgnoreCase("questIcon")) {
			Quest quest = questDAO.readByID(gameObjID);
			if(quest.getIconID()!=null) {
				quest.setIconID(null);
				mediaDAO.delete(quest.getIconID());
			}
			quest.setIconID(mediaID);
			questDAO.update(quest);
		} 
		
	}
}